import dayjs from 'dayjs'

export function time2str(time: string): string {
  if (!time) return '未知时间'
  let date = dayjs(time)
  let year = date.year()
  let month = date.month() + 1
  let day = date.date()

  let nowDate = dayjs()
  let nowYear = nowDate.year()
  let nowMonth = nowDate.month() + 1

  if (year == nowYear) {
    if (month == nowMonth) {
      return geDiffDateCn(day) || time
    } else if (month < nowMonth) {
      return getDiffMonthCn(month) || time
    }
  } else if (year < nowYear) {
    return getDiffYearCn(year) || time
  }
  return time
}

function getDiffYearCn(year: number) {
  let nowDate = dayjs()
  let nowYear = nowDate.year()
  // 上次时间不会超过当前时间
  const diffNum = nowYear - year

  switch (diffNum) {
    case 0:
      return '今年'
    case 1:
      return '去年'
    case 2:
      return '前年'
    default:
      return undefined
  }
}

function getDiffMonthCn(month: number) {
  let nowDate = dayjs()
  let nowMonth = nowDate.month() + 1

  // 上次时间不会超过当前时间
  const diffNum = nowMonth - month

  switch (diffNum) {
    case 0:
      return '当月'
    case 1:
      return '上个月'
    case 2:
      return '前一个月'
    default:
      return undefined
  }
}

function geDiffDateCn(date: number) {
  let nowDate = dayjs()
  let nowDay = nowDate.date()
  // 上次时间不会超过当前时间
  const diffNum = nowDay - date

  switch (diffNum) {
    case 0:
      return '今天'
    case 1:
      return '昨天'
    case 2:
      return '前天'
    default:
      return diffNum + '天前'
  }
}
